package com.ueboot.weishop.admin.batch.tasklet;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.ueboot.core.utils.DateUtils;
import com.ueboot.weishop.entity.order.OrderEnum;
import com.ueboot.weishop.entity.order.OrderIssueEntity;
import com.ueboot.weishop.service.order.OrderIssueService;
import com.ueboot.weishop.service.weixin.MessageData;
import com.ueboot.weishop.service.weixin.WeiXinMessage;
import com.ueboot.weishop.service.weixin.WeiXinService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SendWxSmsStepTasklet implements Tasklet {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private OrderIssueService issueService;
	@Autowired
	private WeiXinService weiXinService;

	@Override
	public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
		List<OrderIssueEntity> issueList = issueService.findBySendDmsStatusAndCancelAndSendSmsStatus(OrderEnum.SEND_STATUS_2, OrderIssueEntity.CANCER_0, OrderEnum.SEND_STATUS_0);
		Date sendSmsDate = new Date();
		issueList.forEach(orderIssue -> {
			orderIssue.setSendSmsStatus(OrderEnum.SEND_STATUS_2);
			orderIssue.setSendSmsTime(sendSmsDate);
			try {
				String validDate = orderIssue.getValidBeginDate() + "-" + orderIssue.getValidEndDate();
				Map<String, String> sendResult = this.sendWeiXinSms(orderIssue.getOpenId(), orderIssue.getName(), orderIssue.getGoodsName(), validDate,orderIssue.getCampaignCode());
				try {
					Map<String, String> wxSmsResult = new HashMap<String, String>();
					wxSmsResult.put("openId", orderIssue.getOpenId());
					wxSmsResult.put("content", JSON.toJSONString(sendResult));
					logger.info(JSON.toJSONString(wxSmsResult));
				} catch (Exception e) {
					logger.error("推送信息打印日志异常！", e);
				}
			} catch (Exception e) {
				logger.error("下发DMS代金券的微信消息推送异常，订单号：{},异常：{}", orderIssue.getSeqNo(), e);
			}
		});
		issueService.save(issueList);
		return RepeatStatus.FINISHED;
	}


	private Map<String, String> sendWeiXinSms(String openId, String name, String goodsName, String validDate,String campaignCode) {
		String accessToken = weiXinService.getAccessToken("公众号");
		WeiXinMessage message = new WeiXinMessage();
		message.setTemplate_id("ALkAlu22RnyXPW4PicaijjjE67P556uVkFilI1wavco");
		message.setTouser(openId);
		String first = "尊敬的车主，您参与一元众筹活动获得的代金券已生效，可即时使用！";
        String remark = "请您在有效期内至全国长安福特授权经销商处使用，感谢您的支持！";
//        if("GFB214/2017-1".equals(campaignCode)||"GFB214/2017-2".equals(campaignCode)||"GFB214/2017-1".equals(campaignCode)||"GFB214/2017-2".equals(campaignCode)){
            remark = "请您在有效期内至您选择的长安福特授权经销商处使用，感谢您的支持！";
//        }
		Map<String, MessageData> messageData = Maps.newHashMap();
		messageData.put("first", new MessageData(first));
		messageData.put("keyword1", new MessageData(name));//券号：
		messageData.put("keyword2", new MessageData(goodsName));//名称：
		messageData.put("keyword3", new MessageData(validDate));//使用时间
		messageData.put("remark", new MessageData(remark));
		message.setData(messageData);
		return weiXinService.doSendMessage(accessToken, message);
	}

}
